# 学生信息管理系统
import os

# 数据文件名称
DATA_FILE = "students.txt"


def load_students():
    """从文件加载学生数据"""
    students = []
    if os.path.exists(DATA_FILE):
        try:
            with open(DATA_FILE, 'r', encoding='utf-8') as f:
                for line in f:
                    # 每行数据格式：学号,姓名,年龄
                    data = line.strip().split(',')
                    if len(data) == 3:
                        student = {
                            'id': data[0],
                            'name': data[1],
                            'age': data[2]
                        }
                        students.append(student)
            print("学生数据加载成功！")
        except Exception as e:
            print(f"加载数据时出错: {e}")
    else:
        print("未找到数据文件，将创建新文件。")
    return students


def save_students(students):
    """保存学生数据到文件"""
    try:
        with open(DATA_FILE, 'w', encoding='utf-8') as f:
            for student in students:
                line = f"{student['id']},{student['name']},{student['age']}\n"
                f.write(line)
        print("数据保存成功！")
    except Exception as e:
        print(f"保存数据时出错: {e}")


def show_menu():
    """显示主菜单"""
    print("\n" + "=" * 30)
    print("    学生信息管理系统")
    print("=" * 30)
    print("1. 添加学生")
    print("2. 删除学生")
    print("3. 修改学生信息")
    print("4. 查询学生")
    print("5. 显示所有学生")
    print("6. 退出系统")
    print("=" * 30)


def add_student(students):
    """添加学生信息"""
    print("\n--- 添加学生 ---")

    while True:
        student_id = input("请输入学号: ").strip()
        if not student_id:
            print("学号不能为空，请重新输入！")
            continue

        # 检查学号是否已存在
        if any(s['id'] == student_id for s in students):
            print("该学号已存在，请重新输入！")
            continue
        break

    name = input("请输入姓名: ").strip()
    if not name:
        print("姓名不能为空！")
        return

    age = input("请输入年龄: ").strip()
    if not age:
        print("年龄不能为空！")
        return

    # 创建学生字典
    student = {
        'id': student_id,
        'name': name,
        'age': age
    }

    # 添加到列表
    students.append(student)
    print(f"成功添加学生：{name} (学号: {student_id})")


def delete_student(students):
    """删除学生信息"""
    if not students:
        print("系统中暂无学生信息！")
        return

    print("\n--- 删除学生 ---")
    student_id = input("请输入要删除的学生学号: ").strip()

    # 查找学生
    for i, student in enumerate(students):
        if student['id'] == student_id:
            print(f"找到学生：{student['name']} (学号: {student_id})")
            confirm = input("确认删除吗？(y/n): ").strip().lower()
            if confirm == 'y':
                del students[i]
                print("删除成功！")
            else:
                print("取消删除。")
            return

    print(f"未找到学号为 {student_id} 的学生！")


def modify_student(students):
    """修改学生信息"""
    if not students:
        print("系统中暂无学生信息！")
        return

    print("\n--- 修改学生信息 ---")
    student_id = input("请输入要修改的学生学号: ").strip()

    # 查找学生
    for student in students:
        if student['id'] == student_id:
            print(f"当前信息：学号: {student['id']}, 姓名: {student['name']}, 年龄: {student['age']}")

            # 获取新信息
            new_name = input(f"请输入新姓名 (当前: {student['name']}): ").strip()
            new_age = input(f"请输入新年龄 (当前: {student['age']}): ").strip()

            if new_name:
                student['name'] = new_name
            if new_age:
                student['age'] = new_age

            print("修改成功！")
            print(f"更新后信息：学号: {student['id']}, 姓名: {student['name']}, 年龄: {student['age']}")
            return

    print(f"未找到学号为 {student_id} 的学生！")


def search_student(students):
    """查询学生信息"""
    if not students:
        print("系统中暂无学生信息！")
        return

    print("\n--- 查询学生 ---")
    print("1. 按学号查询")
    print("2. 按姓名查询")
    choice = input("请选择查询方式: ").strip()

    if choice == '1':
        student_id = input("请输入学号: ").strip()
        for student in students:
            if student['id'] == student_id:
                print(f"查询结果：学号: {student['id']}, 姓名: {student['name']}, 年龄: {student['age']}")
                return
        print(f"未找到学号为 {student_id} 的学生！")

    elif choice == '2':
        name = input("请输入姓名: ").strip()
        found = False
        for student in students:
            if student['name'] == name:
                print(f"查询结果：学号: {student['id']}, 姓名: {student['name']}, 年龄: {student['age']}")
                found = True
        if not found:
            print(f"未找到姓名为 {name} 的学生！")
    else:
        print("无效的选择！")


def show_all_students(students):
    """显示所有学生信息"""
    if not students:
        print("系统中暂无学生信息！")
        return

    print("\n--- 所有学生信息 ---")
    print("学号\t姓名\t年龄")
    print("-" * 20)
    for student in students:
        print(f"{student['id']}\t{student['name']}\t{student['age']}")
    print(f"共 {len(students)} 名学生")


def main():
    """主函数"""
    # 加载学生数据
    students = load_students()

    while True:
        # 显示菜单
        show_menu()

        # 获取用户选择
        choice = input("请选择功能（输入数字）: ").strip()

        # 根据选择执行相应功能
        if choice == '1':
            add_student(students)
        elif choice == '2':
            delete_student(students)
        elif choice == '3':
            modify_student(students)
        elif choice == '4':
            search_student(students)
        elif choice == '5':
            show_all_students(students)
        elif choice == '6':
            # 退出前保存数据
            save_students(students)
            print("谢谢使用！再见！")
            break
        else:
            print("输入有误，请重新输入！")


# 程序入口
if __name__ == "__main__":
    main()